package com.ay7.controller;

import com.ay7.VO.ProductInfoVO;
import com.ay7.VO.ProductVO;
import com.ay7.VO.ResultVO;
import com.ay7.entity.ProductCategory;
import com.ay7.entity.ProductInfo;
import com.ay7.service.ProductCategoryService;
import com.ay7.service.ProductInfoService;
import com.ay7.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 买家商品Controller
 * Created by wenjul
 * on 18/3/25 0025 13:34
 */
@RestController
@RequestMapping("/buyer/product")
//@CacheConfig(cacheNames = "productList")
public class BuyerProductController {

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private ProductInfoService productInfoService;

    @GetMapping("/list")
    @Cacheable(cacheNames = "productList",key = "123") //key默认为方法参数的值,condition输入缓存条件，unless结果缓存条件
    public ResultVO list() {

        //1、查询所有的上架商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();

        //2、查询类目

        List<Integer> categoryTypeList = new ArrayList<>();
        //传统方法
        for (ProductInfo productInfo : productInfoList) {
            categoryTypeList.add(productInfo.getCategoryType());
        }

        //JAVA8 lambda
        categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());

        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(categoryTypeList);

        List<ProductVO> productVOlist=new ArrayList<>();
        List<ProductInfoVO> productInfoVOList=new ArrayList<>();

        //3、数据拼装
        for (ProductCategory productCategory : productCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());


            for (ProductInfo productInfo : productInfoList) {
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
                    ProductInfoVO productInfoVO=new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOlist.add(productVO);
        }
        return ResultVOUtil.success(productVOlist);
    }

}
